package com.woman.beautylive.presentation.ui.room.player;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jakewharton.rxbinding.view.RxView;
import com.pili.pldroid.player.AVOptions;
import com.pili.pldroid.player.PLMediaPlayer;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.pili.pldroid.player.widget.PLVideoView;
import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.R;
import com.woman.beautylive.data.bean.GetFriendBean;
import com.woman.beautylive.data.bean.HotAnchorSummary;
import com.woman.beautylive.data.bean.LoginInfo;
import com.woman.beautylive.data.bean.gift.Gift;
import com.woman.beautylive.data.bean.me.UserInfo;
import com.woman.beautylive.data.repository.SourceFactory;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.base.BaseActivity;
import com.woman.beautylive.presentation.ui.chatting.utils.Event;
import com.woman.beautylive.presentation.ui.main.currency.CurrencyActivity;
import com.woman.beautylive.presentation.ui.main.me.transaction.RechargeActivity;
import com.woman.beautylive.presentation.ui.room.RoomActivity;
import com.woman.beautylive.presentation.ui.room.RoomFragment;
import com.woman.beautylive.presentation.ui.widget.getfriendview.GetFriendLayout;
import com.woman.beautylive.presentation.ui.widget.giftView.GiftClickListener;
import com.woman.beautylive.presentation.ui.widget.giftView.GiftLayoutView;
import com.woman.beautylive.util.Const;
import com.woman.beautylive.util.L;
import com.umeng.analytics.MobclickAgent;
import com.woman.beautylive.util.MrlCountDownTimer;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import com.yqritc.scalablevideoview.ScalableType;
import com.yqritc.scalablevideoview.ScalableVideoView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.jpush.im.android.api.JMessageClient;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * @author Muyangmin
 * @since 1.0.0
 * 观看直播
 */
public class PlayerFragment extends RoomFragment implements PlayerUiInterface{

    private static final String ARG_ANCHOR_SUMMARY = "anchor";
    private static final String ARG_ANCHOR_PLAYURL="backurl";
    private static final String ARG_ANCHOR_ISBACK="isback";

    private HotAnchorSummary mSummary;
    private PlayerPresenter presenter;
    private RoomShareHelper shareHelper;

    private int PAGER_JSON;
    //播放源地址
    private String playbackUrl;

    private View mRoomOwner; //房间主人控件
    private AlertDialog alertDialog;

    private GiftLayoutView mGiftView;
//                          礼物弹出窗
    private View mChargeLay, mGiftLay;
    private TextView mChargeTv, mchargeinforBtn;
    private Button mGiftSentBtn;
    private TextView mGiftContinue;

    private boolean hasSendHeartRequest = false;

    private int giftComboCount;

    private PLVideoView mVideoView;
    private ScalableVideoView mMp4Video;

//    是否是回播
    private boolean isBackPlay=false;
//    回播得到的数据源房间号
    private String roomidmsg;
//    回播地址
    private String backplayurl;
//    回播视频的开始时间
    private String backstarttime;
//    //      弹幕view
//    private IDanmakuView mDanmakuView;
//    //   弹幕分析器
//    private BaseDanmakuParser mParser;
//    //    弹幕context
//    private DanmakuContext mContext;
    RelativeLayout surfaceFrame;
//  记录视频变化
    private int oldWidth=-1,oldHeight=-1;
//    记录获得的信息是否是退出了的
    private boolean isgetTopContributeUsers;
//    自定义的小伙伴view
    private GetFriendLayout getFriendLayout;
    //    复制地址
    private TextView mCopyTv;
    //    触摸移动
    private View moveInculde;
//    计算便宜量
    private float touchMoveX=-1,touchMoveY=-1;
//    记录
    private boolean isHideMove;
    private PLMediaPlayer.OnInfoListener mOnInfoListener = new PLMediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(PLMediaPlayer plMediaPlayer, int what, int extra) {
            L.d(LOG_TAG, "onInfo: " + what + ", " + extra);
            return false;
        }
    };

    private PLMediaPlayer.OnErrorListener mOnErrorListener = new PLMediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(PLMediaPlayer plMediaPlayer, int errorCode) {
            Log.e(LOG_TAG, "Error happened, errorCode = " + errorCode);

            switch (errorCode) {
                case PLMediaPlayer.ERROR_CODE_INVALID_URI:
                    toastShort("Invalid URL !");
                    break;
                case PLMediaPlayer.ERROR_CODE_404_NOT_FOUND:
                    toastShort("404 resource not found !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_REFUSED:
                    toastShort("Connection refused !");
                    break;
                case PLMediaPlayer.ERROR_CODE_CONNECTION_TIMEOUT:
                    toastShort("Connection timeout !");
                    break;
                case PLMediaPlayer.ERROR_CODE_EMPTY_PLAYLIST:
                    toastShort("Empty playlist !");
                    break;
                case PLMediaPlayer.ERROR_CODE_STREAM_DISCONNECTED:
                    toastShort("Stream disconnected !");
                    break;
                case PLMediaPlayer.ERROR_CODE_IO_ERROR:
                    Log.i("mrl","拉流的io异常"+isloginout+isNetworkConnected(getActivity())+" "+mVideoView+" "+backplayurl);
                    if (isloginout) {
                        toastShort("直播间未开播 !");//Network IO Error !//
                        return false;
                    }else if (!isNetworkConnected(getActivity())){
                        toastShort("当前网络不可用");//Network IO Error !//
                        return false;
                    }
                    if (mVideoView!=null&&backplayurl!=null) {
                        mVideoView.setVideoPath(backplayurl);
                        mVideoView.start();
                        return true;
                    }else {
                        toastShort("链接超时咯，或者主播未开播呢");//Network IO Error !//
                        return false;
                    }
                case PLMediaPlayer.MEDIA_ERROR_UNKNOWN:
                default:
                    toastShort("unknown error !");
                    break;
            }
            // Todo pls handle the error status here, retry or call finish()
            ((RoomActivity) getActivity()).finishRoomActivity();

//            mMediaPlayer.reset();
//            mMediaPlayer.setDisplay(mSurfaceView.getHolder());
//            mMediaPlayer.setDataSource(mVideoPath);
//            mMediaPlayer.prepareAsync();


            // If you want to retry, do like this:
            // mVideoView.setVideoPath(mVideoPath);
            // mVideoView.start();
            // Return true means the error has been handled
            // If return false, then `onCompletion` will be called
            return true;
        }
    };

    private PLMediaPlayer.OnCompletionListener mOnCompletionListener = new PLMediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(PLMediaPlayer plMediaPlayer) {
            if (!isgetTopContributeUsers) {
                ((RoomActivity) getActivity()).showRoomEndInfoDialog();
            }
            L.i("mrl", "Play Completed !"+System.currentTimeMillis());
//            if (alertDialog == null) {
//                final BaseActivity activity = (BaseActivity) getActivity();
//                alertDialog = new AlertDialog.Builder(activity)
//                        .setCancelable(false)
//                        .setMessage("主播已离开")
//                        .setPositiveButton("退出", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                ((RoomActivity) getActivity()).finishRoomActivity();
//                            }
//                        })
//                        .create();
//                alertDialog.show();
//            }
//            ((RoomActivity)getActivity()).finishRoomActivity();
        }
    };

    private PLMediaPlayer.OnBufferingUpdateListener mOnBufferingUpdateListener = new PLMediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(PLMediaPlayer plMediaPlayer, int precent) {
            L.d(LOG_TAG, "onBufferingUpdate: " + precent);
        }
    };

    private PLMediaPlayer.OnSeekCompleteListener mOnSeekCompleteListener = new PLMediaPlayer.OnSeekCompleteListener() {
        @Override
        public void onSeekComplete(PLMediaPlayer plMediaPlayer) {
            L.d(LOG_TAG, "onSeekComplete !");
        }
    };

    private PLMediaPlayer.OnVideoSizeChangedListener mOnVideoSizeChangedListener = new PLMediaPlayer.OnVideoSizeChangedListener() {
        @Override
        public void onVideoSizeChanged(PLMediaPlayer plMediaPlayer, int width, int height) {
            L.i("mrl", "onVideoSizeChanged: " + width + "," + height);
            if (oldWidth==-1&&oldHeight==-1) {
                if (width > height) {
                    mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_FIT_PARENT);
                } else {
                    mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_PAVED_PARENT);
                }
                oldWidth = width;
                oldHeight=height;
            }
//            这里判断是否是同样的数据
            if (oldWidth!=width&&oldHeight!=height) {
                if (width > height) {
                    mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_FIT_PARENT);
                } else {
                    mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_PAVED_PARENT);
                }
                Log.i("mrl","进来了几次了");
                oldHeight=height;
                oldWidth=width;
            }
        }
    };

    public static PlayerFragment newInstance(@NonNull Bundle bundle,String roomidmsg,boolean isPlay) {
        PlayerFragment fragment = new PlayerFragment();
        bundle.putString(ARG_ANCHOR_PLAYURL,roomidmsg);
        bundle.putBoolean(ARG_ANCHOR_ISBACK,isPlay);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static Bundle createArgs(@NonNull HotAnchorSummary summary) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(ARG_ANCHOR_SUMMARY, summary);
        return bundle;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_room_player;
    }

    //Mrl L
    public void getViewPagerJson(String user_id, String user_token) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.MAIN_HOST_URL + "/OpenAPI/V1/Anchor/getAnchorBean", RequestMethod.GET);
        request.add("token", user_token);
        request.add("user_id", user_id);
        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, ViewPagerOnResponse);
    }

    private OnResponseListener<JSONObject> ViewPagerOnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            Log.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
                try {
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("douzi", result.getString("data"));
                    msg.what = 1;
                    msg.setData(data);
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            Log.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            Log.i("lll", "viewpager结束了");
            handler.sendEmptyMessage(2);
        }
    };

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                tvGold.setText(msg.getData().getString("douzi"));
            }else if (msg.what==2){
                RelativeLayout.LayoutParams layoutParams =new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                layoutParams.height=getSurfaceViewHeight()-mDanmakuView.getHeight();
                layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                moveInculde.setLayoutParams(layoutParams);
                moveInculde.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction()==MotionEvent.ACTION_DOWN){
                            touchMoveX=event.getX();
                            touchMoveY=event.getY();
                            onRootClickAction();
                        }
                        if (event.getAction()==MotionEvent.ACTION_CANCEL){
                            if (touchMoveX>event.getX()+80&&isHideMove){
//                        显示
                                ObjectAnimator.ofFloat(moveLayout,"X",moveLayout.getWidth(),0).setDuration(1000).start();
                                isHideMove=false;
                            }else if (touchMoveX<event.getX()-80&&!isHideMove){
//                        隐藏
                                ObjectAnimator.ofFloat(moveLayout,"X",0,moveLayout.getWidth()).setDuration(1000).start();
                                isHideMove=true;
                            }
                        }
                        if (event.getAction()==MotionEvent.ACTION_UP){
                            if (touchMoveX>event.getX()+80&&isHideMove){
//                        显示
                                ObjectAnimator.ofFloat(moveLayout,"X",moveLayout.getWidth(),0).setDuration(1000).start();
                                isHideMove=false;
                            }else if (touchMoveX<event.getX()-80&&!isHideMove){
//                        隐藏
                                ObjectAnimator.ofFloat(moveLayout,"X",0,moveLayout.getWidth()).setDuration(1000).start();
                                isHideMove=true;
                            }
                        }
                        return true;
                    }
                });
            }
        }
    };


    @Override
    protected void initViews(View view) {
        super.initViews(view);
        timingLogger.reset(TIMING_LOG_TAG, "PlayerFragment#initViews");
        presenter = new PlayerPresenter(this);
        getFriendLayout= (GetFriendLayout) friendLayout.findViewById(R.id.friend);
        shareHelper = new RoomShareHelper($(view, R.id.room_ll_share), mSummary.getCurrentRoomNum
                (), mSummary.getNickname(),mSummary.getAvatar());

        if (toptabstart!=null){
            toptabstart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (toptabstart.getText().equals(getResources().getString(R.string.room_top_tab_start))){
                        presenter.starUser(LocalDataManager.getInstance().getLoginInfo().getToken(),mSummary.getId(),mSummary.getCurrentRoomNum());
                    }else if (toptabstart.getText().equals(getResources().getString(R.string.room_top_tab_unstart))){
                        presenter.unStarUser(LocalDataManager.getInstance().getLoginInfo().getToken(),mSummary.getId(),mSummary.getCurrentRoomNum());
                    }
                }
            });
        }

        moveInculde=$(view,R.id.room_move_view);
//        initDanmuku(view);

//
//        DisplayMetrics dm = getDisplayMetrics();
//        int initCode = SmartPlayerJni.SmartPlayerInit(getActivity().getApplicationContext(),
//                dm.widthPixels,
//                dm.heightPixels);
//        if (initCode != 0) {
//            L.e(LOG_TAG, "Error init player jni!");
//            return;
//        }
//        if (surfaceView == null) {
//            //TODO consider use dynamic device config list
//            //2nd arg should be false on low devices.
//            surfaceView = NTRenderer.CreateRenderer(getActivity(), true);
//        }
//
//        //2nd arg should be 1 on low devices.
//        SmartPlayerJni.SmartPlayerSetAudioOutputType(surfaceHandle, 0);
//        //noinspection ConstantConditions
//        if (surfaceView == null) {
//            L.e(LOG_TAG, "Error creating surface!");
//            return;
//        }
//        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        lp.height = getSurfaceViewHeight();
//        surfaceView.setLayoutParams(lp);
        //窗口的宽度
//        int screenWidth = dm.widthPixels;
//        FrameLayout surfaceFrame = $(view, R.id.room_player_frame);
//        surfaceFrame.addView(surfaceView);
        //显示主播信息
        SimpleDraweeView draweeAnchor = $(view, R.id.img_user_avatar);
        draweeAnchor.setImageURI(SourceFactory.wrapPathToUri(mSummary.getAvatar()));
        tvOnlineCount.setText(String.valueOf(mSummary.getOnlineCount()));
        if(mSummary.getIs_attention()!=null){
            if (mSummary.getIs_attention().equals("0")){

            }else if (mSummary.getIs_attention().equals("1")){
                toptabstart.setVisibility(View.GONE);
            }
        }
//
//        mCopyTv=$(view, R.id.room_copy_tv);
//        mCopyTv.setVisibility(View.VISIBLE);

        getViewPagerJson(mSummary.getId(), LocalDataManager.getInstance().getLoginInfo().getToken());

        mRoomOwner = $(view, R.id.room_owner);
        RxView.clicks(mRoomOwner).throttleFirst(Const.VIEW_THROTTLE_TIME,
                TimeUnit.MILLISECONDS).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                UserInfo info = new UserInfo();
                info.setId(mSummary.getId());
                info.setNickname(mSummary.getNickname());
                info.setAvatar(mSummary.getAvatar());
                info.setLevel(1 + "");
                info.setSnap(mSummary.getSnap());
                info.setCity(mSummary.getCity());
                showUserInfoDialog(info);
            }
        });


        RxView.clicks($(view, R.id.room_imgbtn_share))
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        shareHelper.showShareLayout(getActivity());
                    }
                });

        RxView.clicks($(view, R.id.room_imgbtn_gift))
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        llOperationBar.setVisibility(View.GONE);
//                        showAnimOut(llOperationBar);
                        mGiftLay.setVisibility(View.VISIBLE);
                        showAnimIn(mGiftLay);
                        recyclerPublicChat.setVisibility(View.GONE);
                    }
                });

//        复制直播地址
//        RxView.clicks(mCopyTv)
//                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
//                .subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//                        android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager)getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
//                        clipboardManager.setText(playbackUrl);
//                        Log.i("mrl","点我啊"+clipboardManager.getText()+playbackUrl);
//                    }
//                });

        mGiftView = $(view, R.id.gift);
        mChargeLay = $(view, R.id.layout_gift_btn_charge);
        mChargeTv = $(view, R.id.layout_gift_charge_tv);
        mchargeinforBtn = $(view, R.id.room_gift_chargeinfor_balance);
        mGiftSentBtn = $(view, R.id.layout_gift_btn_send);
        mGiftContinue = $(view, R.id.layout_gift_btn_continue);
        mGiftLay = $(view, R.id.layout_gift);
        mGiftLay.setVisibility(View.GONE);
        long balance = LocalDataManager.getInstance().getLoginInfo().getTotalBalance();
        mChargeTv.setText(String.valueOf(balance));

        presenter.loadGiftList();
        timingLogger.addSplit("this.initView");
//        判断是否有回播地址1
//        Log.i("mrl","判断是否嘉爱网络地址"+backplayurl+" "+isBackPlay);
//        if (backplayurl!=null&&isBackPlay){
//            this.playbackUrl =backplayurl;
//            mMp4Video.setVisibility(View.GONE);
//            initVideoView();
//            mVideoView.setVideoPath(playbackUrl);
//            mVideoView.start();
//        }else {
//        得到地址
            presenter.loadPlaybackUrl(mSummary.getCurrentRoomNum());
//          得到主播信息，为了获取当前直播状态而已
            presenter.loadUserInfo(mSummary.getId());
            presenter.loadFriendList();
//        }
//        playbackUrl = getPlayerUrl(mSummary.getCurrentRoomNum());
//        L.i(LOG_TAG, "Play URL:  " + playbackUrl);

//        mVideoView = $(view, R.id.room_player_PLVideoView);
//        mVideoView = new PLVideoView(view.getContext());

        surfaceFrame = $(view, R.id.room_player_frame);
        mVideoView= (PLVideoView) surfaceFrame.findViewById(R.id.PLVideoView);
//        mrl的播放器
//        mMp4Video = new ScalableVideoView(getActivity());
        mMp4Video=$(surfaceFrame,R.id.video_view);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);
        lp.height = getSurfaceViewHeight();

        mVideoView.setLayoutParams(lp);
        mMp4Video.setLayoutParams(lp);

//        surfaceFrame.addView(mVideoView);
//        surfaceFrame.addView(mMp4Video);
//        RxView.clicks(mVideoView)
//                .throttleFirst(Const.LIVE_ROOM_HEART_THROTTLE, TimeUnit.MILLISECONDS)
//                .subscribe(new Action1<Void>() {
//                    @Override
//                    public void call(Void aVoid) {
//                        onRootClickAction();
//                    }
//                });
        RxView.clicks(mchargeinforBtn)
                .throttleFirst(Const.LIVE_ROOM_HEART_THROTTLE, TimeUnit.MILLISECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
        mchargeinforBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), RechargeActivity.class);
                startActivity(i);
            }
        });

        //窗口的宽度
//        int screenWidth = dm.widthPixels;
//        FrameLayout surfaceFrame = $(view, R.id.room_player_frame);
//        surfaceFrame.addView(surfaceView);

        timingLogger.addSplit("init url");
//        startPlay();
        timingLogger.addSplit("startPlay");
        timingLogger.dumpToLog();

        if (mRankLay != null) {
            RxView.clicks(mRankLay)
                    .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            showRank();
                        }
                    });
        }


        RxView.clicks($(view, R.id.play_click_view)).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                onRootClickAction();
            }
        });

    }


//    初始化七牛的播放器
    private void initVideoView() {
        AVOptions options = new AVOptions();
        if (isLiveStreaming(playbackUrl)) {
            // the unit of timeout is ms
            options.setInteger(AVOptions.KEY_GET_AV_FRAME_TIMEOUT, 10 * 1000);
            // Some optimization with buffering mechanism when be set to 1
            options.setInteger(AVOptions.KEY_LIVE_STREAMING, 1);
        }

        // 1 -> hw codec enable, 0 -> disable [recommended]
        options.setInteger(AVOptions.KEY_MEDIACODEC, 0);

        // whether start play automatically after prepared, default value is 1
        options.setInteger(AVOptions.KEY_START_ON_PREPARED, 0);

        mVideoView.setAVOptions(options);
        mVideoView.setDisplayAspectRatio(PLVideoView.ASPECT_RATIO_PAVED_PARENT);
        // Set some listeners
        mVideoView.setOnInfoListener(mOnInfoListener);
        mVideoView.setOnVideoSizeChangedListener(mOnVideoSizeChangedListener);
        mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnSeekCompleteListener(mOnSeekCompleteListener);
        mVideoView.setOnErrorListener(mOnErrorListener);

//        mVideoView.setVideoPath(playbackUrl);

        // You can also use a custom `MediaController` widget
//        mMediaController = new MediaController(this, false, isLiveStreaming(mVideoPath));
//        mVideoView.setMediaController(mMediaController);
    }

    /**
     * 展示秀币排行榜
     */
    private void showRank() {
        if (mSummary != null) {
            //TODO 需要添加目前的秀币
            startActivity(CurrencyActivity.createIntent(getActivity(), mSummary.getId(), 0 + ""));
        }
    }

    @Override
    public void showGiftList(final List<Gift> giftList) {
        mGiftView.setGiftDatas(giftList);
        mGiftView.setGiftSelectChangeListener(new GiftClickListener() {
            @Override
            public void onEmotionSelected(boolean isSelect) {
                mGiftSentBtn.setEnabled(isSelect);
            }
        });
        RxView.clicks(mGiftSentBtn)
                .throttleFirst(Const.VIEW_THROTTLE_TIME, TimeUnit.MILLISECONDS)
                //为避免连发过程中取消礼物的选中等导致的数据不一致的异常，这里先做一次Map和filter操作
                //保证最后发送的时候一定会成功。
                .map(new Func1<Void, Gift>() {
                    @Override
                    public Gift call(Void aVoid) {
                        return mGiftView.getSelectedGift();
                    }
                })
                .filter(new Func1<Gift, Boolean>() {
                    @Override
                    public Boolean call(Gift gift) {
                        //没有选中任何礼物则返回false
                        if (gift == null) {
                            return Boolean.FALSE;
                        }
                        long balance = LocalDataManager.getInstance().getLoginInfo()
                                .getTotalBalance();
                        //如果一个都买不起，则返回false并提示充值
                        if (balance < gift.getPrice()) {
                            toastShort("请先充值");
                            return Boolean.FALSE;
                        }
                        return Boolean.TRUE;
                    }
                })
                .doOnNext(new Action1<Gift>() {
                    @Override
                    public void call(Gift gift) {
                        //至少为1
                        giftComboCount = 1;
                    }
                })
                .subscribe(new Action1<Gift>() {
                    @Override
                    public void call(final Gift selectedGift) {
                        mGiftSentBtn.setVisibility(View.INVISIBLE);
                        mGiftContinue.setVisibility(View.VISIBLE);
//                        判断是否是红包
                        if (selectedGift.getIsred().equals("1")){
                            mGiftContinue.setVisibility(View.INVISIBLE);
                            //计算最大合法Combo总数
                            LoginInfo loginInfo = LocalDataManager.getInstance().getLoginInfo();
                            long balance = loginInfo.getTotalBalance();
                            long maxCombo = (int) (balance / selectedGift.getPrice());
                            int finalCombo = giftComboCount > maxCombo ? (int) maxCombo :
                                    giftComboCount;
                            L.d(LOG_TAG, "balance=%d, price=%d, maxCombo=%d, clickCombo=%d, " +
                                            "finally use %d.", balance, selectedGift.getPrice(),
                                    maxCombo, giftComboCount, finalCombo);

                            balance -= (finalCombo * selectedGift.getPrice());
                            L.v(false, LOG_TAG, "update balance to %d.", balance);
                            //直接扣除余额
                            loginInfo.setTotalBalance(balance);
                            //更新到永存
                            LocalDataManager.getInstance().saveLoginInfo(loginInfo);
                            //更新显示
                            mChargeTv.setText(String.valueOf(balance));
                            presenter.sendHongBaoGift(LocalDataManager.getInstance().getLoginInfo().getToken(),mSummary.getId(),selectedGift.getId());
                            mGiftSentBtn.setVisibility(View.VISIBLE);
                            shareHelper.hideShareLayout();
                            llOperationBar.setVisibility(View.VISIBLE);
                            mGiftLay.setVisibility(View.GONE);
                            recyclerPublicChat.setVisibility(View.VISIBLE);
                        }else if (Integer.parseInt(selectedGift.getIsred())>1){
                            mGiftContinue.setVisibility(View.INVISIBLE);
                            //计算最大合法Combo总数
                            LoginInfo loginInfo = LocalDataManager.getInstance().getLoginInfo();
                            long balance = loginInfo.getTotalBalance();
                            long maxCombo = (int) (balance / selectedGift.getPrice());
                            int finalCombo = giftComboCount > maxCombo ? (int) maxCombo :
                                    giftComboCount;
                            L.d(LOG_TAG, "balance=%d, price=%d, maxCombo=%d, clickCombo=%d, " +
                                            "finally use %d.", balance, selectedGift.getPrice(),
                                    maxCombo, giftComboCount, finalCombo);

                            balance -= (finalCombo * selectedGift.getPrice());
                            L.v(false, LOG_TAG, "update balance to %d.", balance);
                            //直接扣除余额
                            loginInfo.setTotalBalance(balance);
                            //更新到永存
                            LocalDataManager.getInstance().saveLoginInfo(loginInfo);
                            //更新显示
                            mChargeTv.setText(String.valueOf(balance));
                            presenter.sendGift(mSummary.getId(), selectedGift.getId(), finalCombo);
                            mGiftSentBtn.setVisibility(View.VISIBLE);
                            shareHelper.hideShareLayout();
                            llOperationBar.setVisibility(View.VISIBLE);
                            mGiftLay.setVisibility(View.GONE);
                            recyclerPublicChat.setVisibility(View.VISIBLE);
                        } else {
//                        礼物连发
                            new MrlCountDownTimer(3000, 100) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    Log.i("mrl",mGiftContinue+" 空么0");
                                    if (mGiftContinue==null){
                                        this.cancel();
                                        return;
                                    }
                                    mGiftContinue.setText(getString(R.string
                                                    .layout_gift_continue_send_default,
                                            millisUntilFinished / 100));
                                }

                                @Override
                                public void onFinish() {
                                    Log.i("mrl",mGiftContinue+" 空么1");
                                    mGiftContinue.setVisibility(View.INVISIBLE);
                                    //计算最大合法Combo总数
                                    LoginInfo loginInfo = LocalDataManager.getInstance().getLoginInfo();
                                    long balance = loginInfo.getTotalBalance();
                                    long maxCombo = (int) (balance / selectedGift.getPrice());
                                    int finalCombo = giftComboCount > maxCombo ? (int) maxCombo :
                                            giftComboCount;
                                    L.d(LOG_TAG, "balance=%d, price=%d, maxCombo=%d, clickCombo=%d, " +
                                                    "finally use %d.", balance, selectedGift.getPrice(),
                                            maxCombo, giftComboCount, finalCombo);

                                    balance -= (finalCombo * selectedGift.getPrice());
                                    L.v(false, LOG_TAG, "update balance to %d.", balance);
                                    //直接扣除余额
                                    loginInfo.setTotalBalance(balance);
                                    //更新到永存
                                    LocalDataManager.getInstance().saveLoginInfo(loginInfo);
                                    //更新显示
                                    mChargeTv.setText(String.valueOf(balance));

                                    presenter.sendGift(mSummary.getId(), selectedGift.getId(), finalCombo);

                                    mGiftSentBtn.setVisibility(View.VISIBLE);
                                }
                            }.start();
                        }
                    }
                });
        RxView.clicks(mGiftContinue)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        giftComboCount++;
                    }
                });
    }

    //    play地址的回调
    @Override
    public void onPlaybackReady(String playbackUrl) {
        this.playbackUrl = playbackUrl;
//        是否是mp4
        if (ismp4(playbackUrl)) {
            mVideoView.setVisibility(View.GONE);
//            surfaceFrame.setVisibility(View.GONE);
//            mRoomScroll.setVisibility(View.GONE);
            initMp4Video(playbackUrl);
        } else {
            //        Log.i("mrl","判断是否嘉爱网络地址"+backplayurl+" "+isBackPlay);
            if (backplayurl!=null&&isBackPlay){
            this.playbackUrl =backplayurl;
            }
            mMp4Video.setVisibility(View.GONE);
            initVideoView();
            mVideoView.setVideoPath(this.playbackUrl);
            mVideoView.start();
        }
    }

    @Override
    public void getStartCode(int code) {
        if (code==0){
            toastShort("关注成功");
            toptabstart.setText("已关注");
            toptabstart.setVisibility(View.GONE);
        }
    }

    @Override
    public void getRemoveStartCode(int code) {
        if (code==0){
            toastShort("取消关注成功");
            toptabstart.setText("关注");
        }
    }

//    得到主播信息的
    @Override
    public void showUserInfo(UserInfo userInfo) {
        if (userInfo.getBroadcasting().equals("n")&&!isBackPlay){
            isgetTopContributeUsers = true;
            isloginout=true;
            ((RoomActivity) getActivity()).showRoomEndInfoDialog();
            mVideoView.stopPlayback();
        }

    }

    @Override
    public void showFriendList(List<GetFriendBean> friendBeanList) {
        getFriendLayout.setFriendList(friendBeanList);
    }


    @Override
    protected void onRootClickAction() {
        super.onRootClickAction();
        shareHelper.hideShareLayout();
        llOperationBar.setVisibility(View.VISIBLE);
        rlPrvChat.setVisibility(View.GONE);
        llSys.setVisibility(View.GONE);
        mGiftLay.setVisibility(View.GONE);
        recyclerPublicChat.setVisibility(View.VISIBLE);
//        try{
//            mConv.resetUnreadCount();
//            dismissSoftInput();
//            JMessageClient.exitConversation();
////                    //发送保存为草稿事件到会话列表
//            if (mIsSingle) {
//                EventBus.getDefault().post(new Event.DraftEvent(mTargetId, mTargetAppKey,
//                        mChatInputEt.getText().toString()));
//            }
//        }catch (Exception e){
//        }
    }

    @Override
    public void onResume() {
        //        如果弹幕不喂空，弹幕是准备的，弹幕之前是暂停的
        if (mDanmakuView != null && mDanmakuView.isPrepared() && mDanmakuView.isPaused()) {
            mDanmakuView.resume();
        }
        mChargeTv.setText(String.valueOf(LocalDataManager.getInstance().getLoginInfo().getTotalBalance()));
        super.onResume();
        if (!TextUtils.isEmpty(playbackUrl)) {
            if (ismp4(playbackUrl)){
            }else {
                mVideoView.start();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDanmakuView != null) {
            // dont forget release!
            mDanmakuView.release();
            mDanmakuView = null;
        }
        if (mMp4Video!=null&&ismp4(playbackUrl)){
            mMp4Video.stop();
            mMp4Video.release();
            mMp4Video=null;
        }

    }


    @Override
    public void onPause() {
        if (mDanmakuView != null && mDanmakuView.isPrepared()) {
            mDanmakuView.pause();
        }
        if (ismp4(playbackUrl)){
        }else {
            mVideoView.pause();
        }
        MobclickAgent.onPageEnd("用户开播");
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        if (mMp4Video!=null&&ismp4(playbackUrl)){
            mMp4Video.stop();
            mMp4Video.release();
            mMp4Video=null;
        }
        super.onDestroyView();
        timingLogger.reset(TIMING_LOG_TAG, "PlayerFragment#onDestroyView");
        mVideoView.stopPlayback();
        shareHelper.unsubscribeAll();
        presenter.unsubscribeTasks();
        L.i(LOG_TAG, "Run into activity destroy++");

        timingLogger.addSplit("unSubscribe tasks");
//        if (surfaceHandle != 0) {
//            Observable.just(surfaceHandle)
//            .subscribeOn(Schedulers.io())
//            .subscribe(new Action1<Long>() {
//                @Override
//                public void call(Long handle) {
//                    TimingLogger logger = new TimingLogger(TIMING_LOG_TAG, "SmartPlayerClose");
//                    SmartPlayerJni.SmartPlayerClose(handle);
//                    logger.addSplit("SmartPlayerClose");
//                    logger.dumpToLog();
//                }
//            });
//            surfaceHandle = 0;
//        }
        timingLogger.addSplit("close native player");
        timingLogger.dumpToLog();
//        这里保险一点，让计时器关闭
        mGiftContinue=null;
    }

    @Override
    protected int getRoomType() {
        return RoomActivity.TYPE_VIEW_LIVE;
    }

//    这里得到传过来的参数
    @Override
    protected void parseArguments(Bundle bundle) {
        isBackPlay=bundle.getBoolean(ARG_ANCHOR_ISBACK);
        roomidmsg=bundle.getString(ARG_ANCHOR_PLAYURL);
        geturldata(roomidmsg);
        mSummary = bundle.getParcelable(ARG_ANCHOR_SUMMARY);
        if (mSummary == null) {
            L.e(LOG_TAG, "Argument is null!");
            toastShort(R.string.msg_argument_error);
        }
        String selfUid = LocalDataManager.getInstance().getLoginInfo().getUserId();
        if (selfUid.equals(mSummary.getId())&&!isBackPlay) {
            toastShort("你不能观看自己的直播");
            ((RoomActivity) getActivity()).finishRoomActivity();
        }
    }

//  试图分解 得到的数据源里面的url地址和start时间
    public void geturldata(String roomidmsg){
        String[] list=roomidmsg.split("_");
        if (list.length>=2){
            this.roomidmsg=list[0];
            backstarttime=list[1];
            backplayurl=list[2];
        }
    }
    @Override
    protected String getWsRoomId() {
        if (isBackPlay){
            return mSummary.getCurrentRoomNum()+backstarttime;
        }else {
            return mSummary.getCurrentRoomNum();
        }
    }
//
//    private DisplayMetrics getDisplayMetrics() {
//        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
//        Display display = wm.getDefaultDisplay();
//        DisplayMetrics dm = new DisplayMetrics();
//        display.getMetrics(dm);
//        L.v(LOG_TAG, "Device display metrics: w=" + dm.widthPixels + ", h=" + dm.heightPixels +
//                ", density=" + dm.density + ", densityDpi=" + dm.densityDpi);
//        return dm;
//    }
//
//    private void startPlay() {
//        L.i(LOG_TAG, "Start playback stream++");
//        surfaceHandle = SmartPlayerJni.SmartPlayerSetSurface(surfaceView);
//
//        if (playbackUrl == null) {
//            L.e(LOG_TAG, "playback URL with NULL...");
//            return;
//        }
//
//        int iPlaybackRet = SmartPlayerJni.SmartPlayerStartPlayback(surfaceHandle, playbackUrl);
//        if (iPlaybackRet != 0) {
//            L.e(LOG_TAG, "StartPlayback stream failed, errorCode=%d", iPlaybackRet);
////            toastShort("播放视频失败，错误码为" + iPlaybackRet);
//            //播放失败一律认为已结束
//            ((RoomActivity)getActivity()).showRoomEndInfoDialog();
//            return;
//        }
//
//        L.i(LOG_TAG, "Start playback stream--");
//    }

    @Override
    protected boolean shouldSendHeartRequest() {
        if (!hasSendHeartRequest) {
            //第一次的时候直接设置为true
            hasSendHeartRequest = true;
            return true;
        }
        return false;
    }

    private boolean isLiveStreaming(String url) {
        if (url.startsWith("rtmp://")
                || (url.startsWith("http://") && url.endsWith(".m3u8"))
                || (url.startsWith("http://") && url.endsWith(".flv"))) {
            return true;
        }
        return false;
    }

    public boolean ismp4(String url) {
        if (url!=null) {
            String suffix = url.substring(url.lastIndexOf(".") + 1);
            if (suffix.equals("mp4")) {
                return true;
            }
        }
        return false;
    }

    private void initMp4Video(String url) {
        try {
            mMp4Video.setDataSource(url);
            mMp4Video.setVolume(100, 100);
            mMp4Video.setScalableType(ScalableType.FIT_XY);
            mMp4Video.setLooping(true);

            mMp4Video.prepareAsync(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });

            mMp4Video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    return false;
                }
            });
            mMp4Video.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                }
            });

            mMp4Video.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(MediaPlayer mp, int what, int extra) {
                    switch(what){
                        case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                            break;
                        case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
                            break;
                        case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                            break;
                        case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                            break;
                    }
                    return false;
                }
            });
        } catch (IOException ioe) {
        }
    }

    public  boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

}
